package com.seezoon.application.device.executor;

import com.seezoon.application.device.dto.SoundRecordingCmd;
import com.seezoon.infrastructure.configuration.context.SecurityContextHolder;
import com.seezoon.infrastructure.dto.Response;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.tcp.codec.JT808;
import com.seezoon.infrastructure.tcp.codec.JTMessage;
import com.seezoon.infrastructure.tcp.codec.JTSerialization;
import com.seezoon.infrastructure.tcp.jt808.JT0001;
import com.seezoon.infrastructure.tcp.jt808.JT8804;
import com.seezoon.infrastructure.tcp.session.Session;
import io.netty.buffer.Unpooled;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

/**
 * 录音
 */
@Slf4j
@RequiredArgsConstructor
@Component
@Validated
public class SoundRecordingExe {

    public Response execute(@NotNull @Valid SoundRecordingCmd cmd) {
        Session session = SecurityContextHolder.getSession();
        JT8804 request = new JT8804();
        request.setCommand(cmd.getCommand());
        request.setTime(cmd.getTime());
        request.setSave(cmd.getSaveFlag());
        request.setAudioSamplingRate(cmd.getSampleRate());
        JTMessage jtMessage = new JTMessage();
        byte[] encode = JTSerialization.encode(request);
        jtMessage.setMsgId(JT808.录音开始命令);
        jtMessage.setMsgProperties(encode.length);
        jtMessage.setSerialNo(session.getClientNo());
        jtMessage.setMsgSerialNo(session.nextSequence());
        jtMessage.setBody(Unpooled.wrappedBuffer(encode));
        JT0001 response = session.send(jtMessage, JT0001.class);
        if (response.isSuccess()) {
            return Response.success();
        }
        return Response.error(ErrorCode.DEVICE_SEND_MSG_ERROR.code(), ErrorCode.DEVICE_SEND_MSG_ERROR.msg());
    }
}
